package misscl.online.slh_gym.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import misscl.online.slh_gym.entity.User;
import misscl.online.slh_gym.service.UserService;
import misscl.online.slh_gym.util.AjaxResult;
import misscl.online.slh_gym.util.JwtUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author theo
 * @since 2022/11/28 22:16
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    //根据电话获取用户
    @GetMapping("/phone/{phone}")
    public User getUserByPhone(@PathVariable("phone") String phone){
        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.eq("phone",phone);
        return userService.getOne(wrapper1);
    }

    //注册用户
    @PutMapping("/phone")
    public User saveByPhone(@RequestBody User user){

        User user1 = user;
        boolean save = userService.save(user1);
        log.info("{}",user);
        log.info("{}",user1);
        return user1;
    }
    @GetMapping("/userInfo")
    private AjaxResult userinfo(HttpServletRequest request){
//       用token获取id
        String authorization = request.getHeader("authorization");

        Integer uid = Integer.valueOf(JwtUtils.getClaimsByToken(authorization).getSubject());

        System.out.println("subject------"+uid);


        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id",uid);
        List list = userService.list(wrapper);

        if (list.size()!=0){

            return AjaxResult.ok("查询用户信息成功").data("userinfo",list);
        }else{

            return AjaxResult.error("查询用户信息失败");
        }
    }
    @PostMapping("/userInfo")
    private AjaxResult userinfo(@RequestBody User user,HttpServletRequest request){

        String authorization = request.getHeader("authorization");

        Integer uid = Integer.valueOf(JwtUtils.getClaimsByToken(authorization).getSubject());

        boolean b = userService.updateById(user);
        if (b){
            return AjaxResult.ok("修改用户信息成功");
        }else{
            return AjaxResult.error("修改用户信息失败");
        }
    }
}
